package projectManagement;

import ch.randelshofer.quaqua.util.Methods;
import java.io.*;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import java.awt.*;
import java.awt.event.*;

import java.util.*;


public class ServerGUI extends JPanel implements ActionListener, WindowListener{
	
	private static final long serialVersionUID = 1L;
	private JButton btnIn;
	private JTextField name;
	private JFrame frame;
	private Editor txtMsg;
	private JPanel discussions;
	private static JPanel profile;
	private static ProfileButton btnPic;
	private JButton btnSend;
	private Server server;
	
	
	private DefaultListModel<String> contactListModel;
	private JList<String> contactList;
	
	
	public ServerGUI(){
		server = null;
		setBackground(new Color(230, 230, 250));
		setOpaque(true);
		setLayout(null);
		setPreferredSize(new Dimension(866, 500));
		
//ALL DISCUSSIONS		
		initDiscussions();
		
// RIGHT PANEL 
// CURRENT CHANNELS n' CONTACTS
		
		JPanel rightPanel = new JPanel();
		rightPanel.setBackground(new Color(135, 206, 235));
		rightPanel.setOpaque(true);
		rightPanel.setBounds(710, 24, 149, 378);
		rightPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
		rightPanel.add(initCurrentChannel());
		rightPanel.add(initContacts());
		
		add(rightPanel);

// CENTER BOTTOM
// INPUT MSG
		
		JPanel msgPanel = new JPanel();
		msgPanel.setBackground(new Color(135, 206, 235));
		msgPanel.setOpaque(true);
		msgPanel.setBounds(120, 406, 739, 87);
		msgPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		msgPanel.add(initTxtMsg());
		
		btnSend = new JButton("Send");
		btnSend.addActionListener(this);
		btnSend.setFont(ch.randelshofer.quaqua.util.Fonts.getEmphasizedDialogFont());
		btnSend.setPreferredSize(new Dimension(140, 70));
		btnSend.putClientProperty("Quaqua.Button.style", "bevel");
		msgPanel.add(btnSend);
		
		add(msgPanel);

//LEFT PANEL
//PROFILE, EMOTICONS, n' CHANNELS
		
		JPanel leftPanel = new JPanel();
		leftPanel.setBackground(new Color(135, 206, 235));
		leftPanel.setOpaque(true);
		leftPanel.setBounds(5, 24, 111, 470);
		leftPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
		leftPanel.add(initProfile());
		leftPanel.add(initChannels());
		
/**
		JButton btnConnect = new JButton("Connect");
		btnConnect.setFont(ch.randelshofer.quaqua.util.Fonts.getMiniDialogFont());
		btnConnect.setPreferredSize(new Dimension(100, 30));
		btnConnect.addActionListener(this);
		leftPanel.add(btnConnect);***/
		leftPanel.add(initEmoticons());

		add(leftPanel);

//CENTER TOP
//WELCOME BANNER
		
		JLabel lblWelcome = new JLabel("Welcome");
		lblWelcome.setBackground(new Color(230, 230, 250));
		lblWelcome.setOpaque(true);
		lblWelcome.setFont(new Font("Tempus Sans ITC", Font.BOLD, 20));
		lblWelcome.setHorizontalAlignment(SwingConstants.CENTER);
		lblWelcome.setBounds(5, 5, 854, 18);
		add(lblWelcome);
		
//FRAME		
		frame = new JFrame("Chat Room");
		frame.getContentPane().setBackground(SystemColor.inactiveCaption);
		frame.setJMenuBar(initMenuBar());
		frame.setPreferredSize(new Dimension(865, 550));
		frame.getContentPane().add(this);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(true);
		frame.setVisible(true);
		frame.pack();
	}

/************************************************************************ MENU BAR ********************************************************************/
 	
	public JMenuBar initMenuBar(){
		JMenuBar menuBar = new JMenuBar();
		JMenu channel = new JMenu("Channel");
		channel.add(new JMenuItem("Author"));
		channel.add(new JMenuItem("Create Channel"));
		
		JMenu about = new JMenu("About");
		menuBar.add(channel);
		menuBar.add(about);
		
		return menuBar;
	}

/********************************************************************* INPUT TEXT AREA ********************************************************************/
	
	public JPanel initTxtMsg(){
		JPanel msgPanel = new JPanel();
		msgPanel.setPreferredSize(new Dimension(580, 75));
		msgPanel.setBounds(128, 370, 372, 77);
		msgPanel.setLayout(new BorderLayout(0, 0));
		
		txtMsg = new Editor();
		txtMsg.setOpaque(true);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setViewportView(txtMsg);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		msgPanel.add(scrollPane, BorderLayout.CENTER);
		
		return msgPanel;
	}

/******************************************************************** EMOTICONS ************************************************************************/
 	
	public JPanel initEmoticons(){
		JPanel emoticons = new JPanel();
		emoticons.setBackground(SystemColor.info);
		emoticons.setOpaque(true);
		emoticons.setPreferredSize(new Dimension(100, 87));
		emoticons.setBorder(new TitledBorder(null, "Emoticons", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		emoticons.setBounds(10, 351, 105, 100);
		System.out.println("emoticons");
		return emoticons;
	}

/****************************************************************** CHANNEL SELECTION ***************************************************************/
	
	public JPanel initChannels(){
		JPanel channels = new JPanel();
		channels.setBackground(new Color(70, 130, 180));
		channels.setOpaque(true);
		channels.setPreferredSize(new Dimension(100, 150));
		channels.setBorder(new TitledBorder(null, "Channels", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		channels.setLayout(new BorderLayout());
		channels.setBounds(10, 184, 105, 131);
		
		
		DefaultListModel<String> channelListModel = new DefaultListModel<>();
		channelListModel.addElement("Channel- 1");
		channelListModel.addElement("Channel- 2");
		
		JList<String> channelList = new JList<>();
		channelList.setFont(new Font("Tempus Sans ITC", Font.PLAIN, 15));
		channelList.setModel(channelListModel);
		channelList.setSelectedIndex(-1);
		channelList.setVisibleRowCount(0);
		channelList.setValueIsAdjusting(true);
		channelList.setLocation(0,0);
		channelList.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		channelList.putClientProperty( "Quaqua.List.style", "striped");
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportView(channelList);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		channels.add(scrollPane, BorderLayout.CENTER);
		
		return channels;
	}
	
/************************************************************************ PROFILE SECTION ***********************************************************/
 
	public JPanel initProfile(){
		name = new JTextField("name");
		name.setHorizontalAlignment(SwingConstants.CENTER);
		name.setBounds(8, 93, 83, 34);
		
		btnIn = new JButton("Start Server");
		btnIn.addActionListener(this);
		btnIn.setFont(new Font("PMingLiU-ExtB", Font.BOLD, 10));
		btnIn.putClientProperty("Quaqua.Button.style", "tableHeader");
		btnIn.putClientProperty("JButton.buttonType", "toolbar");
		btnIn.setBounds(8, 130, 83, 34);
		
		profile = new JPanel();
		profile.setBackground(new Color(70, 130, 180));
		profile.setOpaque(true);
		profile.setPreferredSize(new Dimension(100, 168));
		profile.setBorder(new TitledBorder(null, "ME", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		profile.setLayout(null);
		
		profile.add(name);
		profile.add(btnIn);
		

		btnPic = new ProfileButton();
		btnPic.setActionCommand("Change Pic");
		btnPic.addActionListener(this);
		btnPic.setBounds(5, 17, 90, 75);
		profile.add(btnPic);
		
		return profile;
	}

/************************************************************************* CURRENT CHANNEL **********************************************************/
	
	public JPanel initCurrentChannel(){
		JPanel currentChannel = new JPanel();
		currentChannel.setBackground(new Color(70, 130, 180));
		currentChannel.setOpaque(true);
		currentChannel.setPreferredSize(new Dimension(139, 50));
		currentChannel.setBorder(new TitledBorder(null, "Current Channel", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		currentChannel.setLayout(new BorderLayout(0, 0));
		
		JLabel lblCurrchannel = new JLabel("Channel- 1");
		lblCurrchannel.setOpaque(true);
		lblCurrchannel.setBackground(new Color(230, 230, 250));
		lblCurrchannel.setForeground(new Color(0, 0, 128));
		lblCurrchannel.setHorizontalAlignment(SwingConstants.CENTER);
		currentChannel.add(lblCurrchannel);
		
		return currentChannel;
	}

/******************************************************************** ALL DISCUSSIONS ***********************************************************/
 	
	public void initDiscussions(){
		JPanel panel = new JPanel();
		panel.setBackground(SystemColor.inactiveCaption);
		panel.setBounds(120, 24, 585, 378);
		panel.setOpaque(true);
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Discussions", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(255, 255, 255)));	
		panel.setLayout(new BorderLayout(0, 0));
		
		discussions = new JPanel();
		discussions.setBackground(SystemColor.inactiveCaption);
		discussions.setOpaque(true);
		discussions.setLayout(new GridBagLayout());
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		scrollPane.setViewportView(discussions);
		
		panel.add(scrollPane, BorderLayout.CENTER);
		add(panel);
	}

/************************************************************************** CONTACTS ****************************************************************/
 	
	public JPanel initContacts(){
		JPanel comrade = new JPanel();
		comrade.setBackground(new Color(70, 130, 180));
		comrade.setOpaque(true);
		comrade.setPreferredSize(new Dimension(139, 315));
		comrade.setBorder(new TitledBorder(null, "Comrades", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		comrade.setLayout(new BorderLayout());
		
		contactListModel = new DefaultListModel<>();
		contactListModel.addElement("Bonix");
		contactListModel.addElement("Mond");
		
		contactList = new JList<>();
		contactList.setFont(new Font("Tempus Sans ITC", Font.PLAIN, 15));
		contactList.setModel(contactListModel);
		contactList.setSelectedIndex(-1);
		contactList.setValueIsAdjusting(true);
		contactList.setVisibleRowCount(0);
		contactList.setLocation(0,0);
		contactList.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		contactList.putClientProperty( "Quaqua.List.style", "striped");
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(142, 11, -133, 258);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		scrollPane.setViewportView(contactList);
		comrade.add(scrollPane, BorderLayout.CENTER);
		return comrade;
	}
/************************************************************************************************************************************************/	
// 														UPDATE PROFILE PICTURE
	
	public static void updateProfile(){
		btnPic = new ProfileButton();
		btnPic.setActionCommand("Change Pic");
		btnPic.setBounds(5, 17, 90, 75);
		profile.remove(2);
		profile.repaint();
		profile.add(btnPic);
	}
/************************************************************************************************************************************************/	
// 														LOOK N' FEEL	
	
	public static void setLookAndFeel(){
		   System.setProperty("Quaqua.tabLayoutPolicy", "wrap");
		    if (!System.getProperty("os.name").toLowerCase().startsWith("mac") && !System.getProperty("os.name").toLowerCase().startsWith("darwin")) {
		      try {
		        Methods.invokeStatic(JFrame.class, "setDefaultLookAndFeelDecorated", Boolean.TYPE, Boolean.TRUE);
		        Methods.invokeStatic(JDialog.class, "setDefaultLookAndFeelDecorated", Boolean.TYPE, Boolean.TRUE);
		      }
		      catch (NoSuchMethodException e) {
		        e.printStackTrace();
		      }
		    }
		    try {
		      UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
		    }
		    catch (Exception e) {
		      e.printStackTrace();
		    } 
	}

/************************************************************************************************************************************************/	
// 														START MAIN 
	
	public static void main(String [] args){
		System.out.println("nice");
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					setLookAndFeel();
					new ServerGUI();
				} catch (Exception e) {}
			}
		});
				
	}

/************************************************************************************************************************************************/	
// 														ACTION PERFORM

	@Override
	public void actionPerformed(ActionEvent btn) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		Object button = btn.getSource();
		String send = btn.getActionCommand();
	
		
		if(button == btnPic){
			new ServerProfilePictureSelection();
		}
		
		if(button == btnIn){
			server = new Server(this);
			new ServerRunning().start();
		}
		
		if(send.equalsIgnoreCase("Send")){
			DiscussionMessage msg = new DiscussionMessage(name.getText(), ProfileButton.picture, txtMsg.getText(), sdf.format(new Date())+"", txtMsg.getHeight());
			server.broadcast(msg);
		}
	}
	
/************************************************************************************************************************************************/	
// 														APPEND MESSAGE
	
	public void appendMsg(Message msg){
		PackMessage packMessage = new PackMessage(msg.getAuthor(), msg.getAvatar(), msg.getMsg(), msg.getDate(), msg.getMessageLength());
		
		GridBagConstraints gbc = new GridBagConstraints();
		JPanel comradeMsg = packMessage.getInstance();
		comradeMsg.setOpaque(true);
		
		gbc.gridx = 0;
		gbc.gridy = discussions.getComponentCount();
		
		discussions.revalidate();
		discussions.repaint();
		
		discussions.add(comradeMsg,gbc);
		
	}

/************************************************************************************************************************************************/	
// 													CLOSING FUNCTION
	
	public void windowClosing(WindowEvent e) {

	}
	
	public void windowDeiconified(WindowEvent e) {}
	public void windowActivated(WindowEvent e) {}
	public void windowOpened(WindowEvent e) {}
	public void windowIconified(WindowEvent e) {}
	public void windowClosed(WindowEvent e) {}
	public void windowDeactivated(WindowEvent e) {}
	
	
/************************************************************************************************************************************************/	
// 												START SERVER AS THREAD

	class ServerRunning extends Thread {
		public void run() {
			server.start();         // should execute until if fails
			// the server failed
			//stopStart.setText("Start");
			//tPortNumber.setEditable(true);
			//appendEvent("Server crashed\n");
			//server = null;
		}
	}



	
	
	
	
}
